/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.frontendproject.resolver;

import com.inspur.edp.lcm.metadata.api.entity.FrameWorkTypeEnum;
import com.inspur.edp.web.common.JITEngineConstants;
import com.inspur.edp.web.common.customexception.WebCustomException;
import com.inspur.edp.web.common.entity.TerminalType;
import com.inspur.edp.web.common.environment.ExecuteEnvironment;
import com.inspur.edp.web.common.io.FileUtility;
import com.inspur.edp.web.frontendproject.constant.I18nExceptionConstant;
import com.inspur.edp.web.formmetadata.i18n.constant.I18nResourceConstant;
import com.inspur.edp.web.formmetadata.metadataanalysis.CommandsAnalysis;
import com.inspur.edp.web.formmetadata.resolver.ResolveFormMetadataItem;
import com.inspur.edp.web.formmetadata.resolver.ResolveFormMetadataList;
import com.inspur.edp.web.formmetadata.service.FormMetadataService;
import com.inspur.edp.web.frontendproject.customservice.SourceServicePathGenerator;
import com.inspur.edp.web.frontendproject.entity.ChosenFormList;
import com.inspur.edp.web.frontendproject.metadata.FormMetadataManager;
import com.inspur.edp.web.jitengine.JITEngineManager;
import com.inspur.edp.web.jitengine.expressions.ExpressionManifest;
import com.inspur.edp.web.jitengine.expressions.ExpressionManifestManager;
import com.inspur.edp.web.jitengine.i18nresource.GenerateResourceManager;
import com.inspur.edp.web.jitengine.i18nresource.GeneratedI18nResourceList;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 表单元数据解析
 *
 * @author guozhiqi
 */
public class FormMetadataResolver {

    /**
     * 表单元数据解析
     *
     * @param projectPath
     * @param buildFormList
     */
    public static void resolveFormMetadatas(String projectPath, ChosenFormList buildFormList) {

        if (buildFormList == null) {
            throw new WebCustomException(I18nExceptionConstant.WEB_FRONT_PROJECT_ERROR_0004);
        }
        ResolveFormMetadataList formMetadataList = FormMetadataManager.getFormMetadataList(projectPath, TerminalType.PC, buildFormList);
        if (formMetadataList.isNotEmpty()) {
            // 当前指定表单参与编译 仅影响PC
            resolveFormMetadatas(projectPath, formMetadataList, TerminalType.PC);
        }

        ResolveFormMetadataList mobileFormMetadataList = FormMetadataManager.getFormMetadataList(projectPath, TerminalType.MOBILE, ChosenFormList.getNewInstance());
        if (mobileFormMetadataList.isNotEmpty()) {
            resolveFormMetadatas(projectPath, mobileFormMetadataList, TerminalType.MOBILE);
        }
    }

    /**
     * 解析表单元数据，从 .frm 解析成 .json
     */
    public static void resolveFormMetadatas(String projectPath, ResolveFormMetadataList formMetadataList, TerminalType terminalType) {

        // 获取非解析表单的services目录
        String serviceProductPath = SourceServicePathGenerator.getSourceServiceProductPath(projectPath, terminalType, false);

        // 首先整体移除webdev目录下得services文件目录
        FileUtility.forceDelete(serviceProductPath);

        //获取解析表单的service路径
        String dynamicServiceProductPath = SourceServicePathGenerator.getSourceServiceProductPath(projectPath, terminalType, true);
        FileUtility.forceDelete(dynamicServiceProductPath);


        HashMap<String, CommandsAnalysis.WebComponentMetadataAndExtra> projectCmpList = new HashMap<>();

        for (ResolveFormMetadataItem resolveFormMetadataItem : formMetadataList.getResolveFormMetadataItemList()) {
            GeneratedI18nResourceList i18nResourceList = new GeneratedI18nResourceList();
            GeneratedI18nResourceList zhI18nResourceList = new GeneratedI18nResourceList();
            GeneratedI18nResourceList zhCHTI18nResourceList = new GeneratedI18nResourceList();
            GeneratedI18nResourceList enUKI18nResourceList = new GeneratedI18nResourceList();
            GeneratedI18nResourceList enUSI18nResourceList = new GeneratedI18nResourceList();
            String i18nResourceKeyPrefix = "";

            // 定义表单关联的表达式
            ExpressionManifest expressionManifest = new ExpressionManifest();

            // 解析前检测
            // TODO：尝试获取资源元数据，如果不存在则生成 为了保证中文资源必须存在
            String formPath = resolveFormMetadataItem.getGspMetadata().getRelativePath();

            FormMetadataService formMetadataService = SpringBeanUtils.getBean(FormMetadataService.class);
            formMetadataService.reSaveFormIfResourceNotExists(resolveFormMetadataItem.getGspMetadata(), formPath);

            String targetResolveBasePath = terminalType.getResolveBasePath(projectPath, resolveFormMetadataItem.getCalculateIsDynamicForm());

            if (resolveFormMetadataItem.getCalculateIsDynamicForm()) {
                // 如果是解析表单  那么进行基础路径得修正
                targetResolveBasePath = FileUtility.combine(targetResolveBasePath, resolveFormMetadataItem.getGspMetadata().getHeader().getCode().toLowerCase());
            }

            serviceProductPath = SourceServicePathGenerator.getSourceServiceProductPath(projectPath, terminalType, resolveFormMetadataItem.getCalculateIsDynamicForm());

            // 解析页面流中定义的表单元数据
            Map<String, GeneratedI18nResourceList> i18nResourceListMap = new HashMap<>();
            i18nResourceListMap.put(I18nResourceConstant.En, i18nResourceList);
            i18nResourceListMap.put(I18nResourceConstant.ZH_CHS, zhI18nResourceList);
            i18nResourceListMap.put(I18nResourceConstant.ZH_CHT, zhCHTI18nResourceList);
            i18nResourceListMap.put(I18nResourceConstant.EN_UK, enUKI18nResourceList);
            i18nResourceListMap.put(I18nResourceConstant.EN_US, enUSI18nResourceList);

            JITEngineManager.resolveFormMetadata(resolveFormMetadataItem, formPath, projectPath, targetResolveBasePath, serviceProductPath, projectCmpList,
                    i18nResourceListMap, expressionManifest, i18nResourceKeyPrefix, ExecuteEnvironment.Design, false);

            if (!resolveFormMetadataItem.getCalculateIsDynamicForm()) {
                GenerateResourceManager.generateI18nJsonFile(i18nResourceList, FileUtility.combineOptional(targetResolveBasePath, "i18n", resolveFormMetadataItem.getGspMetadata().getHeader().getCode().toLowerCase(), "i18n"), "");
                GenerateResourceManager.generateI18nJsonFile(zhCHTI18nResourceList, FileUtility.combineOptional(targetResolveBasePath, "i18n", resolveFormMetadataItem.getGspMetadata().getHeader().getCode().toLowerCase(), "i18n"), I18nResourceConstant.ZH_CHT + ".json");
                // 处理多语言，之前处理了en/zh-CHT，新增加en-UK。后续换成获取CAF语言列表，遍历处理。
                GenerateResourceManager.generateI18nJsonFile(enUKI18nResourceList, FileUtility.combineOptional(targetResolveBasePath, "i18n", resolveFormMetadataItem.getGspMetadata().getHeader().getCode().toLowerCase(), "i18n"), I18nResourceConstant.EN_UK + ".json");
                GenerateResourceManager.generateI18nJsonFile(enUSI18nResourceList, FileUtility.combineOptional(targetResolveBasePath, "i18n", resolveFormMetadataItem.getGspMetadata().getHeader().getCode().toLowerCase(), "i18n"), I18nResourceConstant.EN_US + ".json");
                if(resolveFormMetadataItem.getGspMetadata().getProperties()!=null && resolveFormMetadataItem.getGspMetadata().getProperties().getFramework().equals(FrameWorkTypeEnum.Vue)){
                    GenerateResourceManager.generateI18nJsonFile(zhI18nResourceList, FileUtility.combineOptional(targetResolveBasePath, "i18n", resolveFormMetadataItem.getGspMetadata().getHeader().getCode().toLowerCase(), "i18n"), I18nResourceConstant.ZH_CHS + ".json");
                }
            } else {
                GenerateResourceManager.generateI18nJsonFile(i18nResourceList, FileUtility.combineOptional(targetResolveBasePath, "i18n"), "");
                GenerateResourceManager.generateI18nJsonFile(zhCHTI18nResourceList, FileUtility.combineOptional(targetResolveBasePath, "i18n"), I18nResourceConstant.ZH_CHT + ".json");
                // 处理多语言，之前处理了en/zh-CHT，新增加en-UK。后续换成获取CAF语言列表，遍历处理。
                GenerateResourceManager.generateI18nJsonFile(enUKI18nResourceList, FileUtility.combineOptional(targetResolveBasePath, "i18n"), I18nResourceConstant.EN_UK + ".json");
                GenerateResourceManager.generateI18nJsonFile(enUSI18nResourceList, FileUtility.combineOptional(targetResolveBasePath, "i18n"), I18nResourceConstant.EN_US + ".json");
                if(resolveFormMetadataItem.getGspMetadata().getProperties()!=null && resolveFormMetadataItem.getGspMetadata().getProperties().getFramework().equals(FrameWorkTypeEnum.Vue)){
                    GenerateResourceManager.generateI18nJsonFile(zhI18nResourceList, FileUtility.combineOptional(targetResolveBasePath, "i18n"), I18nResourceConstant.ZH_CHS + ".json");
                }
            }
            GenerateResourceManager.generateZhI18nJsonFile(zhI18nResourceList, targetResolveBasePath, String.format("%1$s%2$s", resolveFormMetadataItem.getGspMetadata().getHeader().getFileName().toLowerCase(), JITEngineConstants.ResourceJsonFile));

            // 写入表单表达式json文件 仅在PC下构造表达式
            if (terminalType == TerminalType.PC) {
                ExpressionManifestManager.writeExpressionJson(expressionManifest, targetResolveBasePath, resolveFormMetadataItem.getCalculateIsDynamicForm());
            }
        }

        projectCmpList.clear();
    }


}
